import { createSlice, PayloadAction, createAsyncThunk } from "@reduxjs/toolkit";
import { getCurrentUserInfo } from "@src/service";

export interface UserInfo {
  data: any;
  loading: boolean; // 请求数据中
  error: string | null; // 是否错误
}



const initialState: UserInfo = {
  data: {
    avator: "",
    phone_number: "",
    username: "",
    user:0,
    address:"",
    id:0
  },
  loading: true,
  error: null,
};


export const getUserInfo = createAsyncThunk<any, void, { state: any }>(
  "user/getUserInfo",
  async (params, { rejectWithValue, signal }) => {
    console.log(params, "接口需要的参数111");
    try {
      let abort = () => { };
      signal.addEventListener("abort", () => {
        abort();
      });
      const res = await getCurrentUserInfo({
        abort
      });
      return res.data;
    } catch (error) {
      console.log(error, 111111);
      return rejectWithValue(error);
    }
  }
);


export const UserInfoSlice = createSlice({
  name: "userInfo",
  initialState,
  reducers: {
  },
  extraReducers: {
    [getUserInfo.pending.type]: (state) => {
      state.loading = true;
    },
    [getUserInfo.fulfilled.type]: (state, action) => {
      console.log("userInfo", action.payload);
      if(!action.payload) return;
      const { code, message, data } = action.payload;
      if (Object.is(code, 0)) {
        state.loading = false;
        state.data = data;

      } else {
        state.loading = false;
        state.error = message;
      }
    },
    [getUserInfo.rejected.type]: (state, action: PayloadAction<string | null>) => {
      state.loading = false;
      state.error = action.payload;
    }
  }
});


